<?php

class BtBatteryController extends RController
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
    public $defaultAction = 'admin';
	public $layout='//layouts/lay_column2';
    public $menu=array();
    public $moduleName="电池组";	//此处修改本模块名称
    public $searchByUid=0;
    public $base_id;
    
    public function init()
	{
    	$leftmenu = 'yunying';	//此处修改模块所属菜单
		$this->menu = Yii::app()->params[$leftmenu];
	}

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','views','history','contrast','charts','event'),
				'users'=>array('@'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','updates','handler'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete','deletes'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionViews($id)
	{
		
		$this->render('views',array(
				'model'=>$this->loadBatterys($id),
		));
	}
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	
	public function actionGetDictbatterys()
	{		
		$rs = '';
		$data = DictBattery::model()->findAll('MANCODE_V=:PID',array(':PID'=>$_POST['RECORD_ID']));
		$data=CHtml::listData($data,'RECORD_ID','BATTERYTYPE_V');
		
		$rs .= CHtml::tag('option',array('value'=>'0'),CHtml::encode('请选择电池规格'),true);
		
		if(!empty($data)){
			foreach($data as $value=>$name){
				$rs .= CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
			}
		}
			
		echo $rs;
	}
	
	public function actionCreate()
	{
		$model=new BtBatterys;
		$basetypemodel = new MtsysBasetype;
		$bttypemodel = new DictBattery;
		$manumodel = new DictManufacturer;
		
		
			$mUser=User::model()->findByPk(Yii::app()->user->id);
			$unit_level = $mUser->unit_level;
			$unit_id = $mUser->unit_id;
 
			$bases;
			switch ($mUser->unit_level){
				case 4:
/*					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'BASE_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));*/
					
 					$bases = User::model()->getBases($mUser->id);
					//$bases = MtsysBase::model()->findAll('BASE_ID in (:bids)', array(':bids'=>$mUser->unit_id));
 
					break;
				case 3:
					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'COUNTY_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));
 
					break;
				case 2:
					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'CITY_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));
 
					break;
				case 1:
					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'PROVINCE_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));
 
					break;
				case 0:
					$bases = MtsysBase::model()->findAll();
					break;
				default:
					break;
			}
		$btType = DictBattery::model()->findAll();
		$basetypes = MtsysBasetype::model()->findAll();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['BtBatterys']))
		{
			$model->attributes=$_POST['BtBatterys'];
			$model->BATTERYTYPE_V =  $_POST['DictBattery']['RECORD_ID'];
			$model->MANCODE_V =  $_POST['DictManufacturer']['RECORD_ID'];
			$model->BASE_N =  $_POST['MtsysBase']['BASE_ID'];
			$model->BASE_TYPE = $_POST['MysysBasetype']['RECORD_ID'];
			
			if($model->MANCODE_V == 0 || $model->BATTERYTYPE_V == 0){				
					$error = '请选择制造商和电池规格' ;
					throw new CHttpException(404, $error);							
			}
			//$model->INSTALL_TIME = '2012-12-21';
			
			if($model->save())
				$this->redirect(array('views','id'=>$model->RECORD_ID));
		}
		//////var_dump($base);
		$this->render('create',array(
			'model'=>$model,
			'basetypemodel' => $basetypemodel,
			'bttypemodel' => $bttypemodel,
			'manumodel' => $manumodel,
			'base'=>$bases,
			'basetypes' => $basetypes,
			'btType'=>$btType,
		));
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdates($id)
	{
		//echo "id=".$id; 
		$basetypemodel = new MtsysBasetype;
		$bttypemodel = new DictBattery;
		$manumodel = new DictManufacturer;
		
		////var_dump($id);
		$model=$this->loadBatterys($id);
		//$base = MtsysBase::model()->searchByUserid();
		$btType = DictBattery::model()->findAll();
		
		$mUser=User::model()->findByPk(Yii::app()->user->id);
		$unit_level = $mUser->unit_level;
		$unit_id = $mUser->unit_id;
		
		$base;
		switch ($mUser->unit_level){
			case 4:
				/*					$bases = MtsysBase::model()->findAll(array(
				 'condition' => 'BASE_ID = :unit_id',
				 'params' => array(':unit_id' => $unit_id),
				));*/
					
				$base = User::model()->getBases($mUser->id);
				//$base = MtsysBase::model()->findAll('BASE_ID in (:bids)', array(':bids'=>$mUser->unit_id));
		
				break;
			case 3:
				$base = MtsysBase::model()->findAll(array(
				'condition' => 'COUNTY_ID = :unit_id',
				'params' => array(':unit_id' => $unit_id),
				));
		
				break;
			case 2:
				$base = MtsysBase::model()->findAll(array(
				'condition' => 'CITY_ID = :unit_id',
				'params' => array(':unit_id' => $unit_id),
				));
		
				break;
			case 1:
				$base = MtsysBase::model()->findAll(array(
				'condition' => 'PROVINCE_ID = :unit_id',
				'params' => array(':unit_id' => $unit_id),
				));
		
				break;
			case 0:
				$base = MtsysBase::model()->findAll();
				break;
			default:
				break;
		}
	
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	try {
		if(isset($_POST['BtBatterys']))
		{
			////var_dump("test actionUpdates ");
			//////var_dump($_POST['BtBatterys']);
			$model->attributes=$_POST['BtBatterys'];
			$model->BASE_N =  $_POST['MtsysBase']['BASE_ID'];
			$model->BATTERYTYPE_V =  $_POST['DictBattery']['RECORD_ID'];
			$model->MANCODE_V =  $_POST['DictManufacturer']['RECORD_ID'];
			$model->BASE_TYPE = $_POST['MysysBasetype']['RECORD_ID'];
			
			if($model->MANCODE_V == 0 || $model->BATTERYTYPE_V == 0){
				$error = '请选择制造商和电池规格' ;
				throw new CHttpException(404, $error);
			}
			
			if($model->save()){
				////var_dump("test actionUpdates  ok!");
					$this->redirect(array('views','id'=>$model->RECORD_ID));
			}
			
			//$this->redirect(array('view','id'=>$model->RECORD_ID));
		}
	}catch(	Exception $e ){
			//////var_dump($e.);
			//echo $e;
		}
		$basetypes = MtsysBasetype::model()->findAll();
		$this->render('update_bts',array(
				'model'=>$model,
				'basetypemodel' => $basetypemodel,
				'bttypemodel' => $bttypemodel,
				'manumodel' => $manumodel,
				'base'=>$base,
				'basetypes' => $basetypes,
				'btType'=>$btType,
		));
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$base = MtsysBase::model()->findAll();
		$batterys = BtBatterys::model()->findAll();
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['BtBattery']))
		{
			$model->attributes=$_POST['BtBattery'];
			$model->BASE_N = $_POST['MtsysBase']['BASE_ID'];
			$model->GROUP_V = $_POST['BtBattery']['RECORD_ID'];
			

			if($model->save()){
				$this->redirect(array('view','id'=>$model->RECORD_ID));
			}

		}

		$this->render('update_bt',array(
			'model'=>$model,
				'base'=>$base,
				'batterys'=>$batterys,				
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionHistory($gid, $sid)
	{
		//$model=::model()->findByPk($id);
		//$sql = sprintf("select record_id, FORCASTVOLUME_N ,INTER_N  from bt_rundata where BTRRCORD_V = '%s' ", "2839" );
		//$sql = sprintf("select record_id, FORCASTVOLUME_N ,INTER_N  from bt_rundata where BTKEY_V = '%s' and BTSERIALNO_V = %d", "111112-1", 14);
		
		$sql = sprintf("select record_id, FORCASTVOLUME_N ,INTER_N  from bt_rundata where BTKEY_V = '%s' and BTSERIALNO_V = %d", $gid, $sid);
		//////var_dump($sql);
		$dataProvider = new CSqlDataProvider($sql);
		$data = $dataProvider->getData();
		
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		
		if($data ===null)
			throw new CHttpException(400,'此电池没有历史数据');
	
		$this->render('history',array(
				'data'=>$data,
		));
	}
	
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionCharts($id)
	{
 		//echo $id;
		$sql = sprintf("select record_id, CURVAL_N ,CURINNER_N, STATUS_N  from bt_battery where GROUP_V = '%s' order by record_id", $id);
		$sql_count = sprintf("select count(1)  from bt_battery where GROUP_V = '%s'", $id);
		
		//$sql = sprintf("select record_id, CURVAL_N ,CURINNER_N  from bt_battery where GROUP_V = '111116-1'" );

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		$count_record=Yii::app()->db->createCommand($sql_count)->queryScalar();
		$dataProvider = new CSqlDataProvider($sql,
						array(
								'totalItemCount'=>$count_record,
								'pagination'=>array(
								'pageSize'=>$count_record,
								),
						));
		 
		$data = $dataProvider->getData();
		//////var_dump( $data);
		if($data===null)
			throw new CHttpException(400,'此电池组没有数据');
	
		//$data = $model-
		//////var_dump( $data);

		$this->render('charts',array(
				'data'=>$data,
		));
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionEvent($id)
	{
		$model=BtBattery::model()->findByPk($id);
	
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
	
		if($model===null)
			throw new CHttpException(400,'此电池组没有数据');
	
		$this->render('event',array(
				'model'=>$model,
		));
	}
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		//echo "actionDelete";
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();
			 
			
			//echo "actionDelete";
			//$this->render('index');
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDeletes($id)
	{
		//echo "actionDelete";
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadBatterys($id)->delete();
			
			BtBattery::model()->deleteAll(array(
			'condition' => 'GROUP_V = :bts_id',
			'params' => array(':bts_id' => $id),
			));
			//echo "actionDelete";
			//$this->render('index');
			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}
	
	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('BtBattery');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model ;
		$battery = null;
		$batterys = null;
		$btc;
		$btsc;
		$sql;
		$sqlcount;
		$bases;
		$searchByUid = 0;
		
			//get batterys from userid
			$mUser=User::model()->findByPk(Yii::app()->user->id);
			$unit_level = $mUser->unit_level;
			$unit_id = $mUser->unit_id;
 
			 
			switch ($mUser->unit_level){
				case 4:
/*					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'BASE_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));*/
					 
	 				//echo $mUser->unit_id;
	 				//modified by hyq 2012.12.22
	 				$condition = ' BASE_ID in ('.$mUser->unit_id.')';
					$bases = MtsysBase::model()->findAll($condition);
					//$bases = MtsysBase::model()->findAll(' BASE_ID in (:bids)', array(":bids"=>$mUser->unit_id));
					
					//User::model()->getBases(user->user_id);
						
					break;
				case 3:
					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'COUNTY_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));
 
					break;
				case 2:
					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'CITY_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));
 
					break;
				case 1:
					$bases = MtsysBase::model()->findAll(array(
					'condition' => 'PROVINCE_ID = :unit_id',
					'params' => array(':unit_id' => $unit_id),
					));
 
					break;
				case 0:
					$bases = MtsysBase::model()->findAll();
					//$model =  BtBatterys::model()->findAll();
					$sql = "SELECT  @row := @row +1 AS id,  a.*, c.*  
							FROM mtsys_base a
							JOIN bt_batterys c ON c.BASE_N = a.BASE_ID,
							(SELECT @row :=0)r";
					$sqlcount = "SELECT  count(1)  
							FROM mtsys_base a
							JOIN bt_batterys c ON c.BASE_N = a.BASE_ID";
					$btcount = Yii::app()->db->createCommand($sqlcount)->queryScalar();
					$batterys = new CSqlDataProvider($sql,
							array( 'totalItemCount'=>$btcount,
									'sort'=>array(
											'attributes'=>array(
													'BATTERYTYPE_V','GROUPNAME_V',  'BASE_NAME', 'RECORD_ID',
											),
									),
									'pagination'=>array(
									'pageSize'=>10,
									),
							));
					break;
				default:
					break;
			} 
 
		
			if(isset($_GET['base_id'])){
				 
				if($_GET['base_id'] !=null){
					$batterys = BtBatterys::model()->searchByBid($_GET['base_id']);
					 
				}else 
					$batterys = BtBatterys::model()->searchByUserid();
				$this->searchByUid = 1;
				$this->base_id = $_GET['base_id'];
			}elseif(isset($_GET['BASE_N'])){
				 
				$batterys = BtBatterys::model()->searchByBid($_GET['BASE_N']);
				$this->searchByUid = 1;
				$this->base_id = $_GET['BASE_N'];
			}else{
				 
				$batterys = BtBatterys::model()->searchByUserid();
				$this->searchByUid = 0;
			}
			if(isset($_GET['RECORD_ID'])){
				//echo $_GET['RECORD_ID'];
				$gid = $_GET['RECORD_ID'];
				$battery = BtBattery::model()->findAll("GROUP_V=:gid",array(
				":gid" => $gid ));
				//return;
			}else
				$battery = BtBattery::model()->findAll('GROUP_V = -1');

			 $this->render('admin',array(
			 	'bases'=>$bases,
				'batterys'=>$batterys, 
			 	'battery'=>$battery,
 
			));   
				 
	}
		

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=BtBattery::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadBatterys($id)
	{
		$model=BtBatterys::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='bt-battery-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}


